import json
import os
import time
import logging
import pygame
import requests
import speech_recognition as sr
from concurrent.futures import ThreadPoolExecutor
from settings import *



## Set logger
log_directory = 'logs'
if not os.path.exists(log_directory):
    os.makedirs(log_directory)
logger = logging.getLogger('Logger')
logger.setLevel(logging.DEBUG)

debug_handler = logging.FileHandler(os.path.join(log_directory, 'debug.log'))
debug_handler.setLevel(logging.DEBUG)
debug_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))

error_handler = logging.FileHandler(os.path.join(log_directory, 'error.log'))
error_handler.setLevel(logging.ERROR)
error_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))

info_handler = logging.FileHandler(os.path.join(log_directory, 'info.log'))
info_handler.setLevel(logging.INFO)
info_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))

stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(logging.Formatter('%(asctime)s - %(message)s'))

logger.addHandler(debug_handler)
logger.addHandler(error_handler)
logger.addHandler(info_handler)
logger.addHandler(stream_handler)


class Listener(object):

    def __init__(self):
        self.recognizer = sr.Recognizer()

    def hear(self, audio_path='input.wav'):
        with sr.Microphone() as source:
            input("\n按回车开始说话 ")
            print("开始说话...")
            audio_data = self.recognizer.listen(source, timeout=3, phrase_time_limit=5)
            print("录音已完成")
            with open(audio_path, "wb") as audio_file:
                audio_file.write(audio_data.get_wav_data())

            audio_file = open(audio_path, "rb")
            transcription = client.audio.transcriptions.create(
                model="whisper-1",
                file=audio_file
            )
            return transcription.text


class Speaker(object):
    def __init__(self):
        self.executor = ThreadPoolExecutor(max_workers=1)
        pygame.mixer.init()

    def play_audio(self, audio_path):
        pygame.mixer.music.load(audio_path)
        pygame.mixer.music.play()
        while pygame.mixer.music.get_busy():
            time.sleep(1)

    def say(self, text, model="tts-1", voice="onyx", audio_path='output.mp3'):
        response = client.audio.speech.create(
            model=model,
            voice=voice,
            input=text
        )
        response.stream_to_file(audio_path)
        self.executor.submit(self.play_audio, audio_path)


def chat(question):
    if not question: return
    logger.info(f"Your Question: {question}")
    headers = {"Content-Type": "application/json"}
    data = {"query": question,
            "knowledge_base_name": "qfdg",
            "model_name": "qianfan-api",
            "top_k": 4,
            "score_threshold": 0.6,
            "stream": False,
            "local_doc_url": False,
            "temperature": 0.75,
            "channel": 84,
            "history": []}
    response = requests.post(config_url, headers=headers,
                             data=json.dumps(data))

    # 找到第一个'{'的位置
    index = response.text.find('{')
    s = response.text[index:]
    answer = json.loads(s)['answer']
    logger.info(f"Answer: {answer}")
    return json.loads(s)['answer']
